#include "oled.h"
#include "nrf_delay.h"

// only avaliable for 128x64 ssd1306 oled
#define SSD1306_128_64

#ifdef SSD1306_128_64

#define SSD1306_CONFIG_SCL_PIN      7
#define SSD1306_CONFIG_SDA_PIN      30

#define OLED_BLE_ICON_POS_X 80
#define OLED_BLE_ICON_POS_Y 0
#define OLED_BLE_ICON_WIDTH 7
#define OLED_BLE_ICON_HEIGHT 14

#define OLED_BATTERY_ICON_POS_X 0
#define OLED_BATTERY_ICON_POS_Y 0
#define OLED_BATTERY_ICON_WIDTH 32
#define OLED_BATTERY_ICON_HEIGHT 12

#define OLED_BATTERY_POS_X1 36
#define OLED_BATTERY_POS_X2 48
#define OLED_BATTERY_POS_Y 0
#define OLED_BATTERY_FONTSIZE 2

#define OLED_ADC_FONTSIZE 5
#define OLED_ADC_POS_X1 12
#define OLED_ADC_POS_X2 52
#define OLED_ADC_POS_X3 92
#define OLED_ADC_POS_Y 24

#endif

const unsigned char bluetooth_icon[] =
{
	0X08,0X40,0X04,0X80,0X03,0X00,0X7F,0XF8,0X23,0X10,0X14,0XA0,0X08,0X40  //7x14
};

void user_oled_init() {
	ssd1306_init_i2c(SSD1306_CONFIG_SCL_PIN, SSD1306_CONFIG_SDA_PIN);
	ssd1306_begin(SSD1306_SWITCHCAPVCC, SSD1306_I2C_ADDRESS, false);
	nrf_delay_ms(1);
	ssd1306_clear_display();
	ssd1306_display();
	nrf_delay_ms(1);
}

void _draw_ble(uint8_t px, uint8_t py) {
	uint8_t col, row, i, j, temp;
	col = px+2; row = py;
	for(i = 0; i < OLED_BLE_ICON_HEIGHT; i++) {
		temp = bluetooth_icon[i];
		for(j = 0; j < 8; j++) {
			if(temp & 0x80)
				ssd1306_draw_pixel( col, row, 1);
			temp = temp << 1;
			row ++;
			if(row - py == OLED_BLE_ICON_HEIGHT) {
				row = py;
				col ++;
				break;
			}
		}
	}
	ssd1306_draw_round_rect(px, py, 12, 16, 1, 1);
}

void oled_draw_ble() {
	_draw_ble(OLED_BLE_ICON_POS_X, OLED_BLE_ICON_POS_Y);
}

int8_t user_get_battery() {
	static uint8_t battery = 99;
	battery --;
	if(battery < 1)
		battery = 99;
	return battery;
}

void oled_draw_battery(uint8_t battery) {
	uint8_t width, start;
	uint32_t icon = 0;
	icon = ((uint32_t)battery) * OLED_BATTERY_ICON_WIDTH / 100;
	start = OLED_BATTERY_ICON_WIDTH - (uint8_t)icon;
	width = (uint8_t)icon;
	if(width < 0)
		width = 0;

	ssd1306_draw_rect(OLED_BATTERY_ICON_POS_X, OLED_BATTERY_ICON_POS_Y,
			OLED_BATTERY_ICON_WIDTH, OLED_BATTERY_ICON_HEIGHT, 1);
	ssd1306_fill_rect(start , OLED_BATTERY_ICON_POS_Y,
			width, OLED_BATTERY_ICON_HEIGHT, 1);

	uint8_t c1 = battery / 10 + '0';
	uint8_t c2 = battery % 10 + '0';
	ssd1306_draw_char(OLED_BATTERY_POS_X1, OLED_BATTERY_POS_Y, c1,
			1, 0, OLED_BATTERY_FONTSIZE);
	ssd1306_draw_char(OLED_BATTERY_POS_X2, OLED_BATTERY_POS_Y, c2,
			1, 0, OLED_BATTERY_FONTSIZE);

}

void oled_draw_adc(uint16_t adc_sample) {
	if(adc_sample > 999)
		adc_sample = 999;
	else if(adc_sample < 1)
		adc_sample = 0;
	uint8_t c1 = adc_sample / 100 + '0';
	uint8_t c2 = adc_sample / 10 % 10 + '0';
	uint8_t c3 = adc_sample % 10 + '0';

	ssd1306_draw_char(OLED_ADC_POS_X1, OLED_ADC_POS_Y, c1, 1, 0, OLED_ADC_FONTSIZE);
	ssd1306_draw_char(OLED_ADC_POS_X2, OLED_ADC_POS_Y, c2, 1, 0, OLED_ADC_FONTSIZE);
	ssd1306_draw_char(OLED_ADC_POS_X3, OLED_ADC_POS_Y, c3, 1, 0, OLED_ADC_FONTSIZE);
}
